package com.service.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

/**
 * @author alpha
 * @className: Jsons
 * @date 2022/8/30 20:08
 * @Description
 */
public class Jsons {
    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 把对象转为json字符串
     * @param obj 任意类型
     * @return
     */

    public static String toStr(Object obj) {
        try {
            String s = mapper.writeValueAsString(obj);
            return s;
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 带复杂类型的json字符串逆转成对象
     * @param jsonStr
     * @param tTypeReference
     * @return
     * @param <T>
     */
    public static<T> T  toObj(String jsonStr, TypeReference<T> tTypeReference){
        if (StringUtils.isEmpty(jsonStr)) {
            return null;
        }
        T t = null;
        try {
            t = mapper.readValue(jsonStr, tTypeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }
    /**
     * json字符串转普通对象
     * @param jsonStr
     * @param clazz
     * @return
     * @param <T>
     */
    public static<T> T  toObj(String jsonStr, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonStr)) {
            return null;
        }
        T t = null;
        try {
            t = mapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }
}
